package uk.ac.aber.paws.server.remoteinstall;

import java.util.Hashtable;
import java.util.Vector;
import java.util.logging.Level;

import uk.ac.aber.paws.server.config.Constants;
import uk.ac.aber.paws.server.config.ConfigManager;
import uk.ac.aber.paws.server.core.PAWSInstaller;
import uk.ac.aber.paws.server.db.DBLogger;

/**
 * @author Rob Johnson, Aberystwyth University
 * @email rob.johnson@aber.ac.uk
 * @date 21st May 2012
 * 
 * ProcessInstallRequests.java
 * 
 * This thread constantly polls the database awaiting PAWS install/update requests
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
public class ProcessInstallRequests extends Thread {

	private boolean running;
	private int sleepTime;
	
	public ProcessInstallRequests() {
		
		this.sleepTime = Integer.parseInt(ConfigManager.getProperty("app.remoteinstall.interrupt"));
		this.running = true;
		this.start();
	}
	
	public void run() {
	
		while (running) {
			
			try {
				
				processRequests(PAWSInstaller.getDomain());
				
				this.sleep(this.sleepTime);
			} 
			catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * Queries the database for the given domain and discovers any new PAWS install/update requests. If received, brokers a new 
	 * PAWSClientInstall instantiation to deal with the request.
	 * @param domain
	 */
	private void processRequests(String domain) {
		
		Vector<Hashtable<String,Object>> requests = (new DBLogger()).getPendingInstalls(PAWSInstaller.getDomain(),Constants.PAWSINSTALL_PENDING);
		
		for (int i=0;i<requests.size();i++) {
			
			Hashtable<String,Object> request = requests.get(i);
			
			PAWSInstaller.LOG_FILE.log(Level.ALL,"Processing request: "+request.toString());
			
			int installType = ((Integer)request.get("InstallType")).intValue();
		
			new PAWSClientInstall(request,installType);
		}
	}
	
}
